/*
 * Copyright (c) 2024 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import { ArkClass } from 'arkanalyzer/lib/core/model/ArkClass';
import { BaseChecker, BaseMetaData } from '../BaseChecker';
import Logger, { LOG_MODULE_TYPE } from 'arkanalyzer/lib/utils/logger';
import { Stmt, ArkNewExpr, ArkAssignStmt, ArkMethod, ArkInvokeStmt, Local, Value, FunctionType, ANONYMOUS_CLASS_PREFIX } from 'arkanalyzer';
import { Rule, Defects, ClassMatcher, MatcherTypes, MatcherCallback } from '../../Index';
import { IssueReport } from '../../model/Defects';

const logger = Logger.getLogger(LOG_MODULE_TYPE.HOMECHECK, 'AvoidObjectAllocInBuild');
const gMetaData: BaseMetaData = {
    severity: 3,
    ruleDocPath: 'docs/avoid-object-alloc-in-build.md',
    description: 'It is essential to avoid allocating new objects during rendering or layout calculations.'
};

export class AvoidObjectAllocInBuild implements BaseChecker {
    readonly metaData: BaseMetaData = gMetaData;
    public rule: Rule;
    public defects: Defects[] = [];
    public issues: IssueReport[] = [];

    private clsMatcher: ClassMatcher = {
        matcherType: MatcherTypes.CLASS,
        hasViewTree: true
    };

    public registerMatchers(): MatcherCallback[] {
        const matchClazzCb: MatcherCallback = {
            matcher: this.clsMatcher,
            callback: this.check
        };
        return [matchClazzCb];
    }

    public check = (target: ArkClass): void => {
        const buildMethod = target.getMethodWithName('build');
        if (!buildMethod) {
            return;
        }
        this.processMethod(buildMethod);
    };

    private processMethod(mtd: ArkMethod): void {
        let stmts = mtd.getBody()?.getCfg().getStmts() ?? [];
        for (let stmt of stmts) {
            if (stmt instanceof ArkAssignStmt) {
                let rightOp = stmt.getRightOp();
                if (!(rightOp instanceof ArkNewExpr)) {
                    continue;
                }
                const type = rightOp.getClassType();
                const name = type.getClassSignature().getClassName();
                if (name.startsWith(ANONYMOUS_CLASS_PREFIX)) {
                    continue;
                }
                this.reportIssue(stmt, rightOp);
            } else if (stmt instanceof ArkInvokeStmt) {
                const invokeExpr = stmt.getInvokeExpr();
                const args = invokeExpr.getArgs();
                if (args.length !== 0) {
                    this.getAnonymousFunction(mtd, args);
                }
                const method = mtd.getDeclaringArkFile().getScene().getMethod(invokeExpr.getMethodSignature());
                if (method === null) {
                    continue;
                }
                if (method.getDeclaringArkFile() !== mtd.getDeclaringArkFile()) {
                    continue;
                }
                this.processMethod(method);
            }
        }
    }

    private getAnonymousFunction(mtd: ArkMethod, args: Value[]): void {
        for (let arg of args) {
            if (!(arg instanceof Local)) {
                continue;
            }
            const type = arg.getType();
            if (!(type instanceof FunctionType)) {
                continue;
            }
            const method = mtd.getDeclaringArkFile().getScene().getMethod(type.getMethodSignature());
            if (method === null) {
                continue;
            }
            this.processMethod(method);
        }
    }

    private reportIssue(stmt: Stmt, rightOp: ArkNewExpr): void {
        const severity = this.rule.alert ?? this.metaData.severity;
        const arkFile = stmt.getCfg().getDeclaringMethod().getDeclaringArkFile();
        const originPosition = stmt.getOperandOriginalPosition(rightOp);
        if (arkFile && originPosition) {
            let lineNum = originPosition.getFirstLine();
            let startColumn = originPosition.getFirstCol();
            let endColunm = originPosition.getLastCol() - 1;
            const filePath = arkFile.getFilePath();
            const originText = stmt.getOriginalText();
            if (!originText || originText.length === 0 || !originText.includes('new')) {
                return;
            }
            let defects = new Defects(lineNum, startColumn, endColunm, this.metaData.description, severity, this.rule.ruleId,
                filePath, this.metaData.ruleDocPath, true, false, false);
            this.issues.push(new IssueReport(defects, undefined));
        }
    }
}